/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.plc4x.java.ads.readwrite;

import static org.apache.plc4x.java.spi.codegen.fields.FieldReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.fields.FieldWriterFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataReaderFactory.*;
import static org.apache.plc4x.java.spi.codegen.io.DataWriterFactory.*;
import static org.apache.plc4x.java.spi.generation.StaticHelper.*;

import java.time.*;
import java.util.*;
import org.apache.plc4x.java.api.exceptions.*;
import org.apache.plc4x.java.api.value.*;
import org.apache.plc4x.java.spi.codegen.*;
import org.apache.plc4x.java.spi.codegen.fields.*;
import org.apache.plc4x.java.spi.codegen.io.*;
import org.apache.plc4x.java.spi.generation.*;

// Code generated by code-generation. DO NOT EDIT.

/**
 * An AMS packet can be transferred via RS232 with the help of an AMS serial frame. The actual AMS
 * packet is in the user data field of the frame. The max. length of the AMS packet is limited to
 * 255 bytes. Therefore the max. size of an AMS serial frame is 263 bytes. The fragment number is
 * compared with an internal counter by the receiver. The frame number is simply accepted and not
 * checked when receiving the first AMS frame or in case a timeout is exceeded. The CRC16 algorithm
 * is used for calculating the checksum.
 *
 * @see <a
 *     href="https://infosys.beckhoff.com/content/1033/tcadsamsserialspec/html/tcamssericalspec_amsframe.htm?id=8115637053270715044">TwinCAT
 *     AMS via RS232 Specification</a>
 */
public class AmsSerialFrame implements Message {

  // Properties.
  /** Id for detecting an AMS serial frame. */
  protected final int magicCookie;

  /**
   * Address of the sending participant. This value can always be set to 0 for an RS232
   * communication, since it is a 1 to 1 connection and hence the participants are unique.
   */
  protected final byte transmitterAddress;

  /**
   * Receiver’s address. This value can always be set to 0 for an RS232 communication, since it is a
   * 1 to 1 connection and hence the participants are unique.
   */
  protected final byte receiverAddress;

  /**
   * Number of the frame sent. Once the number 255 has been sent, it starts again from 0. The
   * receiver checks this number with an internal counter.
   */
  protected final byte fragmentNumber;

  /**
   * The max. length of the AMS packet to be sent is 255. If larger AMS packets are to be sent then
   * they have to be fragmented (not published at the moment).
   */
  protected final byte length;

  /** The AMS packet to be sent. */
  protected final AmsPacket userdata;

  protected final int crc;

  public AmsSerialFrame(
      int magicCookie,
      byte transmitterAddress,
      byte receiverAddress,
      byte fragmentNumber,
      byte length,
      AmsPacket userdata,
      int crc) {
    super();
    this.magicCookie = magicCookie;
    this.transmitterAddress = transmitterAddress;
    this.receiverAddress = receiverAddress;
    this.fragmentNumber = fragmentNumber;
    this.length = length;
    this.userdata = userdata;
    this.crc = crc;
  }

  /** Id for detecting an AMS serial frame. */
  public int getMagicCookie() {
    return magicCookie;
  }

  /**
   * Address of the sending participant. This value can always be set to 0 for an RS232
   * communication, since it is a 1 to 1 connection and hence the participants are unique.
   */
  public byte getTransmitterAddress() {
    return transmitterAddress;
  }

  /**
   * Receiver’s address. This value can always be set to 0 for an RS232 communication, since it is a
   * 1 to 1 connection and hence the participants are unique.
   */
  public byte getReceiverAddress() {
    return receiverAddress;
  }

  /**
   * Number of the frame sent. Once the number 255 has been sent, it starts again from 0. The
   * receiver checks this number with an internal counter.
   */
  public byte getFragmentNumber() {
    return fragmentNumber;
  }

  /**
   * The max. length of the AMS packet to be sent is 255. If larger AMS packets are to be sent then
   * they have to be fragmented (not published at the moment).
   */
  public byte getLength() {
    return length;
  }

  /** The AMS packet to be sent. */
  public AmsPacket getUserdata() {
    return userdata;
  }

  public int getCrc() {
    return crc;
  }

  public void serialize(WriteBuffer writeBuffer) throws SerializationException {
    PositionAware positionAware = writeBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();
    writeBuffer.pushContext("AmsSerialFrame");

    // Simple Field (magicCookie)
    writeSimpleField("magicCookie", magicCookie, writeUnsignedInt(writeBuffer, 16));

    // Simple Field (transmitterAddress)
    writeSimpleField("transmitterAddress", transmitterAddress, writeSignedByte(writeBuffer, 8));

    // Simple Field (receiverAddress)
    writeSimpleField("receiverAddress", receiverAddress, writeSignedByte(writeBuffer, 8));

    // Simple Field (fragmentNumber)
    writeSimpleField("fragmentNumber", fragmentNumber, writeSignedByte(writeBuffer, 8));

    // Simple Field (length)
    writeSimpleField("length", length, writeSignedByte(writeBuffer, 8));

    // Simple Field (userdata)
    writeSimpleField("userdata", userdata, writeComplex(writeBuffer));

    // Simple Field (crc)
    writeSimpleField("crc", crc, writeUnsignedInt(writeBuffer, 16));

    writeBuffer.popContext("AmsSerialFrame");
  }

  @Override
  public int getLengthInBytes() {
    return (int) Math.ceil((float) getLengthInBits() / 8.0);
  }

  @Override
  public int getLengthInBits() {
    int lengthInBits = 0;
    AmsSerialFrame _value = this;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    // Simple field (magicCookie)
    lengthInBits += 16;

    // Simple field (transmitterAddress)
    lengthInBits += 8;

    // Simple field (receiverAddress)
    lengthInBits += 8;

    // Simple field (fragmentNumber)
    lengthInBits += 8;

    // Simple field (length)
    lengthInBits += 8;

    // Simple field (userdata)
    lengthInBits += userdata.getLengthInBits();

    // Simple field (crc)
    lengthInBits += 16;

    return lengthInBits;
  }

  public static AmsSerialFrame staticParse(ReadBuffer readBuffer) throws ParseException {
    readBuffer.pullContext("AmsSerialFrame");
    PositionAware positionAware = readBuffer;
    boolean _lastItem = ThreadLocalHelper.lastItemThreadLocal.get();

    int magicCookie = readSimpleField("magicCookie", readUnsignedInt(readBuffer, 16));

    byte transmitterAddress = readSimpleField("transmitterAddress", readSignedByte(readBuffer, 8));

    byte receiverAddress = readSimpleField("receiverAddress", readSignedByte(readBuffer, 8));

    byte fragmentNumber = readSimpleField("fragmentNumber", readSignedByte(readBuffer, 8));

    byte length = readSimpleField("length", readSignedByte(readBuffer, 8));

    AmsPacket userdata =
        readSimpleField(
            "userdata", readComplex(() -> AmsPacket.staticParse(readBuffer), readBuffer));

    int crc = readSimpleField("crc", readUnsignedInt(readBuffer, 16));

    readBuffer.closeContext("AmsSerialFrame");
    // Create the instance
    AmsSerialFrame _amsSerialFrame;
    _amsSerialFrame =
        new AmsSerialFrame(
            magicCookie,
            transmitterAddress,
            receiverAddress,
            fragmentNumber,
            length,
            userdata,
            crc);
    return _amsSerialFrame;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof AmsSerialFrame)) {
      return false;
    }
    AmsSerialFrame that = (AmsSerialFrame) o;
    return (getMagicCookie() == that.getMagicCookie())
        && (getTransmitterAddress() == that.getTransmitterAddress())
        && (getReceiverAddress() == that.getReceiverAddress())
        && (getFragmentNumber() == that.getFragmentNumber())
        && (getLength() == that.getLength())
        && (getUserdata() == that.getUserdata())
        && (getCrc() == that.getCrc())
        && true;
  }

  @Override
  public int hashCode() {
    return Objects.hash(
        getMagicCookie(),
        getTransmitterAddress(),
        getReceiverAddress(),
        getFragmentNumber(),
        getLength(),
        getUserdata(),
        getCrc());
  }

  @Override
  public String toString() {
    WriteBufferBoxBased writeBufferBoxBased = new WriteBufferBoxBased(true, true);
    try {
      writeBufferBoxBased.writeSerializable(this);
    } catch (SerializationException e) {
      throw new RuntimeException(e);
    }
    return "\n" + writeBufferBoxBased.getBox().toString() + "\n";
  }
}
